/************** 注意：此文件中的代码，不要做任何修改 ****************/
const config = require("./config");
const axios = require("axios");

// 导入 dayjs 模块
const dayjs = require("dayjs");
// 导入 dayjs 插件
const weekday = require("dayjs/plugin/weekday");
const isSameOrAfter = require("dayjs/plugin/isSameOrAfter");
let isBirthDayLoveStr = "";
// 使用 dayjs 插件
dayjs.extend(weekday);
dayjs.extend(isSameOrAfter);

axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

const axiosPost = function (url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
const axiosGet = function (url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 获取token
async function getToken() {
  const params = {
    grant_type: "client_credential",
    appid: config.app_id,
    secret: config.app_secret,
  };
  let res = await axiosGet("https://api.weixin.qq.com/cgi-bin/token", params);
  return res.data.access_token;
}
// 获取天气情况
async function get_weather() {
  const params = {
    openId: "aiuicus",
    clientType: "h5",
    sign: "h5",
    city: config.city,
  };
  let res = await axiosGet(
    `http://autodev.openspeech.cn/csp/api/v2.1/weather`,
    params
  );
  return res.data.data.list[0];
}
get_weather();

// 获取当前时间：格式 2022年8月25日 星期五
function getCurrentDate() {
  let days = "";
  switch (
    dayjs().weekday() // 当前星期几
  ) {
    case 1:
      days = "星期一";
      break;
    case 2:
      days = "星期二";
      break;
    case 3:
      days = "星期三";
      break;
    case 4:
      days = "星期四";
      break;
    case 5:
      days = "星期五";
      break;
    case 6:
      days = "星期六";
      break;
    case 0:
      days = "星期日";
      break;
  }
  return dayjs().format("YYYY-MM-DD") + " " + days;
}

// 计算生日还有多少天
// function brthDate(brth) {
//   return dayjs(brth).diff(dayjs(), 'day')
// }
function brthDate(brth, who) {
  const nowDate = dayjs().format("YYYY-MM-DD"); // 当前日期（格式：年-月-日）
  brth = brth.replace(
    new Date(brth).getFullYear(),
    new Date(nowDate).getFullYear()
  );
  let birthDays = "";
  // 判断一个日期是否大于等于另一个日期：判断生日 是否大于等于 当前日期（返回布尔值）
  if (dayjs(brth).isSameOrAfter(nowDate)) {
    // 生日还没过
    birthDays = dayjs(brth).diff(dayjs(), "day"); // 获取两个日期相差的天数
  } else {
    // 生日已过,计算距离下一次生日还有多少天
    let nextBirthYears = dayjs().year() + 1; // 下一次生日年份等于当前年份+1
    let nextBirth = nextBirthYears + "-" + dayjs(brth).format("MM-DD"); // 下一次生日年月日
    birthDays = dayjs(nextBirth).diff(dayjs(), "day"); // 获取两个日期相差的天数
  }
  if (birthDays === 0) {
    if (who == 1) {
      isBirthDayLoveStr = "今天是我家丸子的生日，生日快乐呀~";
    } else {
      isBirthDayLoveStr =
        "今天是我的生日，老婆满足我一个小愿望吧~咱~咱还是不要去蹦极吧!";
    }
  }

  return birthDays;
}

// 土味情话
async function sweetNothings() {
  let res = await axiosGet("https://api.1314.cool/words/api.php?return=json");
  let str = "";
  config.loveStr ? (str = config.loveStr) : (str = res.data.word);
  return str.replace(/<br>/g, "\n");
}
sweetNothings();

// 随机颜色
function randomColor() {
  let randomColor =
    "#" +
    parseInt(Math.random() * 0x1000000)
      .toString(16)
      .padStart(6, "0");
  return randomColor;
}
function getwindPower(wind) {
  return parseInt(wind.replace(/[^\d]/g, ""));
}
function getLoveWordStr(index, weatherInfo, loveStr) {
  // 每日情话
  if (index == 0) {
    return isBirthDayLoveStr || loveStr;
  } else if (index == 1) {
    if (
      weatherInfo.weather.includes("晴") ||
      weatherInfo.weather.includes("多云")
    ) {
      return "该干饭干饭啦，傻丸子，出门注意防晒哦，别晒成小黑妞了哦，我可不要非洲妞，小傻瓜~";
    } else if (
      weatherInfo.weather.includes("雨") &&
      !weatherInfo.weather.includes("雷") &&
      !weatherInfo.weather.includes("暴") &&
      !weatherInfo.weather.includes("大") &&
      !weatherInfo.weather.includes("雪") &&
      !weatherInfo.weather.includes("特")
    ) {
      return "该干饭干饭啦，傻丸子，出门注意记得带伞哦，别淋成落汤鸡啦，不然回家就直接拔毛炖了你~";
    } else if (
      weatherInfo.weather.includes("尘") ||
      weatherInfo.weather.includes("霾") ||
      weatherInfo.weather.includes("沙") ||
      weatherInfo.weather.includes("雾")
    ) {
      return "该干饭干饭啦，傻丸子，空气质量不是太好哦，出门要戴口罩，别吸了一鼻子灰哦~";
    } else {
      return "宝贝丸子，该干饭干饭啦，这鬼天气就别想出门了，给老子乖乖呆在家里，哪都不许去~";
    }
  } else {
    if (
      (weatherInfo.weather.includes("晴") ||
        weatherInfo.weather.includes("多云") ||
        weatherInfo.weather.includes("阴")) &&
      !weatherInfo.weather.includes("雨") &&
      !weatherInfo.weather.includes("雪")
    ) {
      if (getwindPower(weatherInfo.wind) < 5) {
        return (
          "报告丸子机长,该干饭干饭啦，天气良好、风速" +
          weatherInfo.wind +
          "，请求起飞~"
        );
      } else {
        return (
          "报告丸子机长,该干饭干饭啦，天气良好、但风速过高，目前" +
          weatherInfo.wind +
          "，慎重起飞~建议滚去陪老公打机！"
        );
      }
    } else if (
      weatherInfo.weather.includes("尘") ||
      weatherInfo.weather.includes("霾") ||
      weatherInfo.weather.includes("沙") ||
      weatherInfo.weather.includes("雾")
    ) {
      if (getwindPower(weatherInfo.wind) < 5) {
        return (
          "报告丸子机长,该干饭干饭啦，可见度低、风速" +
          weatherInfo.wind +
          "，可以起飞~但不要飞远，怕丢了~"
        );
      } else {
        return (
          "报告丸子机长,该干饭干饭啦，可见度低、但风速过高，目前" +
          weatherInfo.wind +
          "，慎重起飞~建议滚去陪老公打机！"
        );
      }
    } else {
      return (
        "报告丸子机长,该干饭干饭啦，天气不好、风速" +
        getwindPower(weatherInfo.wind) +
        "级，禁止起飞~滚去陪老公打机！"
      );
    }
  }
}
async function templateMessageSend(index) {
  let loveStr = await sweetNothings();
  const token = await getToken();
  const url =
    "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +
    token;
  // 天气信息
  let weatherInfo = await get_weather();
  // 计算在一起的天数
  let together_day = dayjs().diff(config.love_date, "day");
  // 模板id 配置项
  const params = {
    touser: config.user,
    template_id: config.template_ids[index],
    url: "http://weixin.qq.com/download",
    topcolor: "#FF0000",
    data: {
      // 当前日期
      nowDate: {
        value: getCurrentDate(),
        color: randomColor(),
      },
      // 省份
      province: {
        value: weatherInfo.province,
        color: randomColor(),
      },
      // 城市
      city: {
        value: weatherInfo.city,
        color: randomColor(),
      },
      // 天气
      weather: {
        value: weatherInfo.weather,
        color: randomColor(),
      },
      // 当前气温
      temp: {
        value: weatherInfo.temp + "°C",
        color: randomColor(),
      },
      // 最低气温
      low: {
        value: weatherInfo.low + "°C",
        color: randomColor(),
      },
      // 最高气温
      high: {
        value: weatherInfo.high + "°C",
        color: randomColor(),
      },
      // 风向
      wind: {
        value: weatherInfo.wind,
        color: randomColor(),
      },
      // 空气质量
      airQuality: {
        value: weatherInfo.airQuality,
        color: randomColor(),
      },
      // 湿度
      humidity: {
        value: weatherInfo.humidity,
        color: randomColor(),
      },
      // 我家丸子的名字
      dearName: {
        value: config.birthday1.name,
        color: randomColor(),
      },
      // 我的名字
      myName: {
        value: config.birthday2.name,
        color: randomColor(),
      },
      // 距离我家丸子生日
      dearBrthDays: {
        value: brthDate(config.birthday1.birthday, 1),
        color: randomColor(),
      },
      // 距离我的生日
      myBrthDays: {
        value: brthDate(config.birthday2.birthday, 2),
        color: randomColor(),
      },
      // 在一起的天数
      loveDays: {
        value: together_day,
        color: randomColor(),
      },
      // 每日情话
      loveWords: {
        value: getLoveWordStr(index, weatherInfo, loveStr),
        color: randomColor(),
      },
    },
  };
  let res = await axiosPost(url, params);
  switch (res.data.errcode) {
    case 40001:
      console.log("推送消息失败,请检查 appId/appSecret 是否正确");
      break;
    case 40003:
      console.log("推送消息失败,请检查微信号是否正确");
      break;
    case 40037:
      console.log("推送消息失败,请检查模板id是否正确");
      break;
    case 0:
      console.log("推送消息成功");
      break;
  }
}
// 调用函数，推送模板消息
// templateMessageSend(0); // 第一次执行程序时会推送一次消息，如使用定时器

// 定时器（Cron）：定时推送消息
const schedule = require("node-schedule");
const scheduleCronstyle = () => {
  // 每天的早8点触发（定时器规则：秒/分/时/日/月/年，*号可理解为"每"的意思，如 0 0 8 * 这个*表示每日）
  // let strArr = ["0 0 8 * * *", "0 0 12 * * *", "0 0 18 * * *"];
  let strArr = ["0 59 7 * * *", "0 59 11 * * *", "0 59 17 * * *"];
  strArr.forEach((item, index) => {
    schedule.scheduleJob(item, () => {
      templateMessageSend(index);
    });
  });
};
scheduleCronstyle();
